package com.qkun.library.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.util.SparseArray;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.qkun.library.base.BaseActivity;
import com.qkun.library.base.IActivityFragmentCompat;

import java.util.ArrayList;
import java.util.List;

/**
 * @author qinkun
 * @date 5/24 0028 21:10
 * @description 结果处理者，用于请求和处理 result
 */
public final class ResultProcessor {

    private static final OnActivityCallback DEFAULT_ACTIVITY_CALLBACK = new OnActivityCallback() {
        @Override
        public void onActivityResult(int resultCode, Intent data) {
            MyLog.d("resultCode: " + resultCode + " data: " + MyLog.getIntentString(data));
        }
    };

    private static final OnPermissionsCallback DEFAULT_PERMISSIONS_CALLBACK = new OnPermissionsCallback() {
        @Override
        public void onGranted(@NonNull String permission) {
            MyLog.d("permission: " + permission);
        }

        @Override
        public void onDenied(@NonNull String permission) {
            MyLog.d("permission: " + permission);
        }
    };

    private static final SparseArray<OnActivityCallback> sActivityCallbacks = new SparseArray<>();
    private static final SparseArray<OnPermissionsCallback> sPermissionsCallbacks = new SparseArray<>();

    private ResultProcessor() {
    }

    public static void clear() {
        sActivityCallbacks.clear();
        sPermissionsCallbacks.clear();
    }

    /**
     * 拨号授权
     * {@link Manifest.permission#CALL_PHONE}
     * 网络授权
     * {@link Manifest.permission#INTERNET}
     * 文件读写授权
     * {@link Manifest.permission#READ_EXTERNAL_STORAGE}
     * {@link Manifest.permission#WRITE_EXTERNAL_STORAGE}
     * 定位授权
     * {@link Manifest.permission#ACCESS_FINE_LOCATION}
     * {@link Manifest.permission#ACCESS_COARSE_LOCATION}
     *
     * @param baseActivity
     * @param permissions
     * @param callback
     */
    public static void requestPermissions(BaseActivity baseActivity, @NonNull String[] permissions, OnPermissionsCallback callback) {
        if (ArraysEx.isEmpty(permissions)) return;
        final int REQUEST_CODE = sPermissionsCallbacks.size() + 1;
        if (Utils.isNull(callback)) {
            callback = DEFAULT_PERMISSIONS_CALLBACK;
        }
        sPermissionsCallbacks.append(REQUEST_CODE, callback);
        List<String> deniedPermissions = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(baseActivity, permission) == PackageManager.PERMISSION_DENIED) {
                deniedPermissions.add(permission);
            } else {
                callback.onGranted(permission);
            }
        }
        if (deniedPermissions.size() > 0) {
            ActivityCompat.requestPermissions(baseActivity, deniedPermissions.toArray(new String[0]), REQUEST_CODE);
        } else {
            sPermissionsCallbacks.delete(REQUEST_CODE);
        }
    }

    public static void startActivityForResult(IActivityFragmentCompat activityFragmentCompat, Intent intent, OnActivityCallback callback) {
        if (!Utils.isOfActivity(intent)) return;
        final int REQUEST_CODE = sActivityCallbacks.size() + 1;
        if (Utils.isNull(callback)) {
            callback = DEFAULT_ACTIVITY_CALLBACK;
        }
        sActivityCallbacks.append(REQUEST_CODE, callback);
        try {
            activityFragmentCompat.startActivityForResult(intent, REQUEST_CODE);
        } catch (Exception e) {
            MyLog.e(e);
            onActivityResult(REQUEST_CODE, BaseActivity.RESULT_FAIL, new Intent());
        }
    }

    /**
     * @param requestCode
     * @param resultCode  该值不一定是{@link Activity#RESULT_OK} {@link Activity#RESULT_CANCELED}
     *                    {@link Activity#RESULT_FIRST_USER}  {@link BaseActivity#RESULT_FAIL}，
     *                    也可能是其他由子Activity通过其setResult()方法返回的值
     * @param data
     */
    public static void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        OnActivityCallback callback = sActivityCallbacks.get(requestCode, DEFAULT_ACTIVITY_CALLBACK);
        if (Utils.nonNull(callback)) {
            callback.onActivityResult(resultCode, data);
        }
        sActivityCallbacks.delete(requestCode);
    }

    /**
     * 会遍历申请的权限数组，逐个回调{@link OnPermissionsCallback#onDenied(String)} {@link OnPermissionsCallback#onGranted(String)}，
     * 因此，在使用{@link OnPermissionsCallback#onDenied(String)} {@link OnPermissionsCallback#onGranted(String)}的时候需要做好判断
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    public static void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        OnPermissionsCallback callback = sPermissionsCallbacks.get(requestCode, DEFAULT_PERMISSIONS_CALLBACK);
        if (Utils.nonNull(callback)) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    callback.onGranted(permissions[i]);
                } else {
                    callback.onDenied(permissions[i]);
                }
            }
        }
        sPermissionsCallbacks.delete(requestCode);
    }

    public interface OnActivityCallback {
        void onActivityResult(int resultCode, Intent data);
    }

    public interface OnPermissionsCallback {
        void onGranted(@NonNull String permission);

        void onDenied(@NonNull String permission);
    }

}

